<template>
  <div ref="xwin" style="height:100%;width:100%;padding: 5px;">
  </div>
</template>

<script>
import chartOption from '@/views/zutai/components/config-json/chart-option.js';
import BaseView from '@/views/zutai/components/topo/control/View';
import {getToken} from "@/utils/auth";
import request from '@/utils/request';


export default {
  name: "ChartWrapper",
  extends: BaseView,
  data() {
    return {
      echart: null,
      timer: null,
    }
  },
  computed: {
    echartRun() {
      return this.detail.dataBind.echartOption + this.detail.dataBind.echartRun;
    }
  },
  watch: {
    echartRun(newColor, oldColor) {
      // console.log('',newColor);
      this.$nextTick(async function () {
        if (this.detail.dataBind.echartOption && (this.detail.dataBind.echartRun > new Date().getTime() - 1000)) {
          let funStr = chartOption.getFun(this.detail.dataBind.echartOption);
          try {
            let echartData = {};
            if (this.detail.dataBind.echartData) {
              try {
                echartData = JSON.parse(this.detail.dataBind.echartData);
              } catch (error) {
                this.$message({
                  message: '请输入正确的json数据',
                  type: 'warning'
                });
              }
            }
            let fun = new Function('request, echarts, echartData', funStr)
            let option = await fun(request, this.$echarts, echartData)
            this.loadData(option);
            this.onResize();
          } catch (error) {
            console.log(error);
            this.$message({
              message: '图表初始化失败，请检查代码视图！',
              type: 'warning'
            });
          }
        }
      });
    }
  },
  methods: {
    loadData(option) {
      if (this.echart) {
        this.echart.dispose();
      }
      let view = this.$refs.xwin;
      this.echart = this.$echarts.init(view);
      this.echart.setOption(option);
    },
    onResize(size) {
      if (this.echart) {
        this.echart.resize();
      }
    },
    async initEchart() {
      if (!this.detail.dataBind.echartOption) {
        this.detail.dataBind.echartOption = chartOption.getOption();
        let funStr = chartOption.getFun(this.detail.dataBind.echartOption);
        let echartData = {};
        if (this.detail.dataBind.echartData) {
          echartData = JSON.parse(this.detail.dataBind.echartData);
        }
        // console.log('echartData', echartData);
        let fun = new Function('request, echarts, echartData', funStr);
        let option = await fun(request, this.$echarts, echartData);
        this.loadData(option);
        this.onResize();
      } else if (this.detail.dataBind.echartOption.indexOf('echartId-') > -1) {
        let id = this.detail.dataBind.echartOption.split("-")[1]
        this.getEchartDataById(id);
      } else {
        let funStr = chartOption.getFun(this.detail.dataBind.echartOption);
        let echartData = {};
        if (this.detail.dataBind.echartData) {
          echartData = JSON.parse(this.detail.dataBind.echartData);
        }
        // console.log('echartData', echartData);
        let fun = new Function('request, echarts, echartData', funStr);
        let option = await fun(request, this.$echarts, echartData);
        setTimeout(() => {
          this.loadData(option);
          this.onResize();
        }, 500);
      }
    },
    getEchartDataById(id) {
      let url = "/zutai/bEchartType/" + id
      request({
        url: url,
        method: "get",
      }).then(async (response) => {
        let funStr = chartOption.getFun(response.data.echartData);
        let echartData = {};
        if (this.detail.dataBind.echartData) {
          echartData = JSON.parse(this.detail.dataBind.echartData);
        }
        let fun = new Function('request, echarts, echartData', funStr);
        let option = await fun(request, this.$echarts, echartData);
        this.loadData(option);
        this.onResize();
        this.detail.dataBind.echartOption = response.data.echartData;
      })
    },
    sendHttpRequestOld() {
      // console.log('发起请求',this.configObject.dataBind);
      let url = this.detail.dataBind.url;
      let method = this.detail.dataBind.method;
      let params = {};
      let paramData = this.detail.dataBind.paramData;
      for (let itemindex = 0; itemindex < paramData.length; itemindex++) {
        //$set()方法第一个参数是对象，第二个参数是key值，第三个参数是value值
        if (paramData[itemindex].key) {
          this.$set(params, paramData[itemindex].key, paramData[itemindex].value);
        }
      }
      let data = {};
      let bodyDataTable = this.detail.dataBind.bodyDataTable;
      for (let itemindex = 0; itemindex < bodyDataTable.length; itemindex++) {
        //$set()方法第一个参数是对象，第二个参数是key值，第三个参数是value值
        if (bodyDataTable[itemindex].key) {
          this.$set(data, bodyDataTable[itemindex].key, bodyDataTable[itemindex].value);
        }
      }
      let headers = {};
      let headerData = this.detail.dataBind.headerData;
      for (let itemindex = 0; itemindex < headerData.length; itemindex++) {
        //$set()方法第一个参数是对象，第二个参数是key值，第三个参数是value值
        if (headerData[itemindex].key) {
          this.$set(headers, headerData[itemindex].key, headerData[itemindex].value);
        }
      }
      let contentType = '';
      if (this.detail.dataBind.contentType == 2) {
        contentType = 'multipart/form-data'
      } else if (this.detail.dataBind.contentType == 3) {
        contentType = 'application/x-www-form-urlencoded;charset=utf-8'
      } else if (this.detail.dataBind.contentType == 4) {
        contentType = 'application/json;charset=utf-8'
        data = this.detail.dataBind.bodyDataArea
      } else if (this.detail.dataBind.contentType == 5) {
        contentType = 'text/xml'
        data = this.detail.dataBind.bodyDataArea
      } else {
        contentType = 'application/json;charset=utf-8'
        data = {};
      }
      request({
        url: url,
        method: method,
        'Content-Type': contentType,
        params: params,
        headers: headers,
        data: data,
        requestType: '数据引擎'
      }).then((res) => {
        // console.log('接口请求成功',res);
        this.detail.dataBind.echartData = JSON.stringify(res.data);
        this.initEchart();
      })
    },
    sendHttpRequest() {
      // console.log('发起请求',this.configObject.dataBind);
      let url = this.detail.dataBind.url;
      let method = this.detail.dataBind.method;
      let data = {};
      let bodyDataTable = this.detail.dataBind.bodyDataTable;
      for (let itemindex = 0; itemindex < bodyDataTable.length; itemindex++) {
        //$set()方法第一个参数是对象，第二个参数是key值，第三个参数是value值
        if (bodyDataTable[itemindex].key) {
          this.$set(data, bodyDataTable[itemindex].key, bodyDataTable[itemindex].value);
        }
      }
      let contentType = '';
      if (this.detail.dataBind.contentType == 2) {
        contentType = 'multipart/form-data'
      } else if (this.detail.dataBind.contentType == 3) {
        contentType = 'application/x-www-form-urlencoded;charset=utf-8'
      } else if (this.detail.dataBind.contentType == 4) {
        contentType = 'application/json;charset=utf-8'
        data = this.detail.dataBind.bodyDataArea
      } else if (this.detail.dataBind.contentType == 5) {
        contentType = 'text/xml'
        data = this.detail.dataBind.bodyDataArea
      } else {
        contentType = 'application/json;charset=utf-8'
        data = {};
      }
      let postUrl = "/zutai/bEchartType/sendHttpRequest"
      let postData = {
        url: url,
        method: method,
        contentType: contentType,
        params: this.detail.dataBind.paramData,
        headers: [
          ...this.detail.dataBind.headerData,
          {
            key: "Authorization",
            value: "Bearer " + getToken()
          }
        ],
        data: JSON.stringify(data),
      }
      request({
        url: postUrl,
        method: "post",
        data: postData,

      }).then((res) => {
        // console.log('sendHttpRequest-获取成功!',res);
        if (res.code == 200) {
          this.detail.dataBind.echartData = res.data;
          this.initEchart();
        }
      })
    },
  },
  mounted() {
    if (!this.editMode && this.detail.dataBind.url) {
      let interval = this.detail.dataBind.interval;
      let intervalType = this.detail.dataBind.intervalType;
      let multiple = 1000;//默认秒，1秒=1000毫秒
      if (intervalType == '分') {
        multiple = 1000 * 60
      } else if (intervalType == '时') {
        multiple = 1000 * 60 * 60
      }
      if (!interval) {
        interval = 60 * 1000;
      } else {
        interval = interval * multiple;
      }
      this.sendHttpRequest()
      this.timer = setInterval(() => {
        this.sendHttpRequest()
      }, interval);
    } else {
      this.initEchart();
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null;
  },
}
</script>
